var App = App||{};
App.Project = { favItems: [], items: [] };

App.Project.init = function(){
	var self = this;
	$('#projectFilterField')
		.bind('keyup click change', function(e){ self.filter.call(self, this.value); })
		.val('');
	
	$('#sidebar')
		.delegate('.project', 'dblclick', function(){ self.editProject.call(self, this); })
		.delegate('.project .star', 'click', function(){
			var star = $(this), project = star.closest('li'), isOn = project.hasClass('fav'), projectId = project.data('projectId');
			if (!isOn) self.addToFavs.call(self, projectId);
			else self.removeFromFavs.call(self, projectId);
		});
	
	$('#editProjectForm').dialog({ autoOpen: false, width: 340, modal: true, title: 'Edit Project', resizable: false,
		close: function(){ resetForm($('#editProjectForm')); },			
		buttons: { Save: $.proxy(this.editProjectSubmit, this), Close: function(){$(this).dialog('close');} }
	});

	$('#sidebar .show-more-projects').bind('click', $.proxy(this.expandProjects, this) );
	$('#sidebar .hide-more-projects').bind('click', $.proxy(this.collapseProjects, this) );
	this.collapseProjects();	
	
	this.load();
};



/*** VIEW ************************************************************************************************************************/
App.Project.reloadLists = function(){ App.Project.load(); };

App.Project.filter = function(word){
	var i=0, item, filtered = [], reg = new RegExp('('+word+')', "i");
	for (; item = this.items[i++] ;){
		if (reg.test(item.name) || reg.test(item.tags)) filtered.push({ id: item.id, name: item.name, tags: item.tags, isFav: item.isFav });
	}
	App.Project.expandProjects();
	this.populateProjects(filtered, word);
};

App.Project.populateProjects = function(items, word){
	if (!items || !items.length) $('#projectList').hide();
	else {
		var list = [], i=0, item;
		for(; item = items[i++] ;) list.push(this.getProjectHtml(item)); 
		$('#projectList').html(list.join('')).show();	
	}
	this.initProjectDD();
};


App.Project.populateFavProjects = function(items){
	if (!items || !items.length) $('#favList').text('').hide();
	else {
		var list = [], i=0, item;
		for(; item = items[i++] ;) list.push(this.getProjectHtml(item)); 
		$('#favList').html(list.join('')).show();
		this.initProjectDD();
	}
};


App.Project.expandProjects = function(e){
	$('#sidebar .show-more-projects').hide();
	$('#sidebar .hide-more-projects').show();
	if (e) $('#projectFilterField').val('');
	App.Project.populateProjects(this.items);
	this.expanded = true;
	return false;
};

App.Project.collapseProjects = function(){
	$('#sidebar .hide-more-projects').hide();
	$('#sidebar .show-more-projects').show();
	$('#projectList').html('').hide();
	$('#projectFilterField').val('');
	this.expanded = false;
	return false;
};


App.Project.editProject = function(project){
	var $pr = $(project),
		data = {
			id: $pr.data('projectId'), 
			name: project.childNodes[1].textContent, 
			tags: $pr.find('.tags').text()
		};
	
	fillForm($('#editProjectForm'), data);
	$('#editProjectForm').dialog('open');	
};
/*********************************************************************************************************************************/




/*** CONTROLER *******************************************************************************************************************/
App.Project.editProjectSubmit = function(){
	var data = serializeForm($('#editProjectForm')), pr = $('#sidebar #project'+data.id);
	$.ajax({ url: "updateProject", context: this, data: data})
	.success(function(data){
		if (!data || data.result == 'error' || data.result == 'auth'){ App.Error(data); return; }
		
		var tags = pr.find('.tags');
		if (data.tags.length){
			if (tags.length) tags.text(data.tags);
			else pr.append('<span class="tags">'+data.tags+'</span>');
		}
		else tags.remove();
		
		msgbox('Project has been updated');
		$('#editProjectForm').dialog('close');
	});
};

App.Project.initProjectDD = function(){
	$("#sidebar .lists li" ).draggable('destroy').draggable({ helper: 'clone', appendTo: 'body', scroll: false, revert: 'invalid', distance: 10 });
};

App.Project.addToFavs = function(projectId){
	$.ajax({ url: "favProject", context: this, data: { projectId: projectId }})
	.success(function(data){
		if (!data || data.result == 'error' || data.result == 'auth'){ App.Error(data); return; }
		this.reloadLists();
	});	
};

App.Project.removeFromFavs = function(projectId){
	$.ajax({ url: "unfavProject", context: this, data: { projectId: projectId }})
	.success(function(data){
		if (!data || data.result == 'error' || data.result == 'auth'){ App.Error(data); return; }
		this.reloadLists();
	});	
};

App.Project.load = function(){
	$.ajax({ url: "project", context: this})
	.success(function(data){
		if (!data || data.result == 'error' || data.result == 'auth'){ 
			App.Error(data);
			$('#sidebar').hide();
			return; 
		}
		this.favItems = this.getFavProjects(data);
		this.items = this.getProjects(data);
		this.populateFavProjects(this.favItems);
		
		if (this.expanded){
			var word = $('#projectFilterField').val();
			if (word.length) this.filter(word);
			else this.populateProjects(this.items);
		}
		
		if (!this.favItems.length) this.expandProjects();		
	});	
};

App.Project.getFavProjects = function(items){
	var list = [], i=0, item;
	for(; item = items[i++] ;) if (item.isFav) list.push(item);
	return list;
};

App.Project.getProjects = function(items){
	var list = [], i=0, item;
	for(; item = items[i++] ;) if (!item.isFav) list.push(item);
	return list;
};

App.Project.getProjectHtml = function(proj){
	var html = [];
	html.push('<li id="project', proj.id, '" data-project-id="' + proj.id + '" class="project', (proj.isFav?' fav':''),'"><span class="star"></span>', proj.name);
	if (proj.tags) html.push('<span class="tags">', proj.tags, '</span>');
	html.push('</li>');
	return html.join(''); 
};
/*********************************************************************************************************************************/
